<template>
  <div class="major" style="margin-top: 30px">
    <div class="major-left">院校省份</div>
    <div class="major-right">
      <div
        v-for="(item, idx) in provincelist"
        :key="idx"
        class="major-size"
        :class="{ active: provinceIndexs.includes(idx) }"
        @click="handleSchoolSelection('province', idx, item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
  <div class="major">
    <div class="major-left">院校类型</div>
    <div class="major-right">
      <div
        v-for="(item, index) in schoolType"
        :key="index"
        class="major-size"
        :class="{ active: typeIndexs.includes(index) }"
        @click="handleSchoolSelection('type', index, item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
  <div class="major">
    <div class="major-left">院校层次</div>
    <div class="major-right alitem">
      <div
        v-for="(item, ids) in studentType"
        :key="ids"
        class="major-size"
        :class="{ active: featureIndexs.includes(ids) }"
        @click="handleSchoolSelection('school_feature', ids, item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
  <div class="major">
    <div class="major-left">院校性质</div>
    <div class="major-right alitem">
      <div
        v-for="(item, index) in natureTypelist"
        :key="index"
        class="major-size"
        :class="{ active: natureTypeIndex.includes(index) }"
        @click="handleSchoolSelection('nature', index, item)"
      >
        {{ item }}
      </div>
      <!-- <el-divider direction="vertical" /> -->
      <div
        v-for="(item, index) in fTypelist"
        :key="index"
        class="major-size"
        :class="{ active: schoolTypeIndexs.includes(index) }"
        @click="handleSchoolSelection('school_type', index, item)"
      >
        {{ item }}
      </div>
      <!-- <el-divider direction="vertical" /> -->
      <div
        v-for="(item, index) in schoolNewlylist"
        :key="index"
        class="major-size"
        :class="{ active: schoolNewlyIndexs.includes(index) }"
        @click="handleSchoolSelection('schoolNewly', index, item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
  <el-row class="matop" v-if="isSelectedSubjects">
    <el-col :span="12">
      <div class="alitem" style="position: relative">
        <!-- <div class="major-left">意向院校</div> -->
        <el-input
          ref="buttonRef"
          v-model="searchKey"
          style="width: 240px"
          placeholder="输入意向院校"
          clearable
          @input="searchKeyInput"
          @focus="isShowSearchPop = true"
          @blur="isShowSearchPop = false"
        >
          <template #prefix>
            <el-icon class="el-input__icon">
              <search />
            </el-icon>
          </template>
        </el-input>
        <div
          v-show="isShowSearchPop && searchList.length > 0"
          class="search-popover"
        >
          <div
            v-for="(item, index) in searchList"
            :key="index"
            @mousedown.native="onClickSearchItem(item, index)"
          >
            <div style="padding: 5px 0">
              {{ index == 0 ? '在筛选条件中搜索 "' + item + '"' : item.cnName }}
            </div>
            <div
              v-if="index + 1 < searchList.length"
              style="width: 100%; height: 1px; background-color: #eee"
            ></div>
          </div>
        </div>
        <div style="margin: 0 6px 0 20px">
          <el-checkbox
            v-model="isAllchecked"
            :label="`考生关注(${props.schoolData.length})`"
            size="large"
            :disabled="props.schoolData?.length == 0"
            @change="toggleAll"
          />
        </div>
        <div style="margin-top: 4px">
          <el-popover
            :visible="visible"
            ref="myPopover"
            placement="bottom"
            :width="180"
            v-model:visible="showPopover"
          >
            <span v-if="props.schoolData.length == 0"
              >暂无关注的意向院校...</span
            >
            <div
              style="display: flex; flex-direction: column"
              v-for="(item, index) in props.schoolData"
              :key="index"
            >
              <el-checkbox-group v-model="Cities.checkedCities">
                <el-checkbox
                  @change="changeItem"
                  :value="item"
                  :label="item.cnName"
                  size="large"
                />
              </el-checkbox-group>
            </div>
            <div
              style="display: flex; justify-content: flex-end"
              v-if="props.schoolData.length != 0"
            >
              <el-button
                type="primary"
                size="small"
                @mousedown.native="schoolSubmit"
                >确定</el-button
              >
            </div>

            <template #reference>
              <el-icon
                @click="visible = !visible"
                class="el-icon--right"
                size="16"
              >
                <ArrowDown />
              </el-icon>
            </template>
          </el-popover>
        </div>
      </div>
    </el-col>
    <el-col v-if="idDrawer" :span="12">
      <div class="flexend right">
        <div>快速通道</div>
        <div class="alitem" @click="fastTrack(1, '3-1')">
          <el-icon size="20">
            <Memo />
          </el-icon>
          院校库
        </div>
        <div class="alitem" @click="fastTrack(3)">
          <el-icon size="20">
            <Histogram />
          </el-icon>
          分数线
        </div>
        <div class="alitem" @click="fastTrack(4)">
          <el-icon size="20">
            <List />
          </el-icon>
          一分一段
        </div>
        <div class="alitem" @click="fastTrack(5)">
          <el-icon size="20">
            <List />
          </el-icon>
          同分去向
        </div>
      </div>
    </el-col>
  </el-row>

  <Drawertool ref="drawertoolRef" />
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { searchSchool, searchSchoolFilter } from '@/api/appv2/appv1.js';
import userSearch from '@/store/modules/searchInfo.js';
import userSearchTool from '@/store/modules/searchInfoTool.js';
// 工具箱专业库开设院校仓库
import userSearchMajorTool from '@/store/modules/searchInfoMajorTool.js';
// 抽屉
import Drawertool from '@/components/Drawertool/';

import _ from 'lodash';
import { ElMessage } from 'element-plus';

const drawertoolRef = ref(null);

const userSearchVal = userSearch();
const userSearchValTool = userSearchTool();
const userSearchValMajorTool = userSearchMajorTool();

const props = defineProps({
  studentId: {
    type: Number,
    default: 0,
  },
  storeType: {
    type: Number,
  },
  idDrawer: {
    type: Boolean,
  },
  zntbProvinceId: {
    type: Number,
    default: 0,
  },
  zntbScore: {
    type: Number,
    default: 0,
  },
  schoolData: {
    type: Object,
    default: () => [],
  },
  isSelectedSubjects: {
    type: Boolean,
    default: true,
  },
  batch: {
    type: Number,
    default: 0,
  },
});
const Cities = reactive({
  checkedCities: [],
});
const visible = ref(false);
const searchList = ref([]); // 模糊搜索数据源
// 筛选数据
const studentType = ref([]); // 院校层次
const provincelist = ref([]); // 省份
const schoolType = ref([]); // 学校类型
const natureTypelist = ref([]); // 学校类型
const fTypelist = ref({}); // 学校类型
const schoolNewlylist = ref([]); // 学校类型

// 选中的筛选下标数据
const provinceIndexs = ref(['0']); // 院校省份 '0' 全国
const typeIndexs = ref([0]); // 院校类型 0 不限
const featureIndexs = ref([0]); // 院校层次 0 不限
const natureTypeIndex = ref([]); // 院校性质 公办、民办、中外/港澳
const schoolTypeIndexs = ref([]); // 院校性质 本科、专科
const schoolNewlyIndexs = ref([]); // 院校性质 新增、非新增

// 选中的筛选数据 格式 [...,{type:'类型', code:'id', name:'标题'},...]
const provinceArray = ref([]); // 院校省份
const typeArray = ref([]); //  院校类型
const levelArray = ref([]); // 院校层次
const natureArray = ref([]); // 院校性质
const searchArray = ref([]); // 搜索

const selItemArray = ref([]); // 所有已选筛选条件

const searchKey = ref(''); // 搜索关键词
const isShowSearchPop = ref(false); // 是否显示搜索pop
const isAllchecked = ref(false);
const schoolList = ref([]);

/**
 * 删除某条筛选条件
 * @param {Object} item {type:'类型', code:'id', name:'标题'}
 */
function deleteScreenItem(item) {
  handleSchoolSelection(item.type, item.code, item.name);
}

function deleteAll() {
  provinceIndexs.value = ['0'];
  typeIndexs.value = [0];
  featureIndexs.value = [0];
  natureTypeIndex.value = [];
  schoolTypeIndexs.value = [];
  schoolNewlyIndexs.value = [];

  provinceArray.value = [];
  typeArray.value = [];
  levelArray.value = [];
  natureArray.value = [];
  searchArray.value = [];
  if (props.storeType == 1) {
    userSearchValTool.saveSchoolInfoChange([]);
  } else if (props.storeType == 2) {
    userSearchValMajorTool.saveSchoolInfoChange([]);
  } else {
    userSearchVal.saveSchoolInfoChange([]); // 保存到 store 中
  }
}

/**
 * @param {Object} type province-院校省份 type-院校类型 school_feature-院校层次 nature-院校性质>办学类型 school_type-院校性质>办学层次 schoolNewly-院校性质>更多筛选
 * @param {Number} code 筛选ID
 * @param {Object} name 筛选标题
 */
function handleSchoolSelection(type, code, name) {
  const selectedItem = {
    code: code,
    name: name,
    type: type,
  };
  if (type === 'schoolNewly') {
    // 院校性质  新增、非新增
    if (schoolNewlyIndexs.value.includes(code)) {
      schoolNewlyIndexs.value = schoolNewlyIndexs.value.filter(
        (i) => i !== code
      );
      natureArray.value = natureArray.value.filter((obj) => obj.code !== code);
    } else {
      schoolNewlyIndexs.value.push(code);
      natureArray.value.push(selectedItem);
    }
  }
  if (type === 'school_type') {
    // 院校性质  本科、专科
    if (schoolTypeIndexs.value.includes(code)) {
      schoolTypeIndexs.value = schoolTypeIndexs.value.filter((i) => i !== code);
      natureArray.value = natureArray.value.filter((obj) => obj.code !== code);
    } else {
      schoolTypeIndexs.value.push(code);
      natureArray.value.push(selectedItem);
    }
  }
  if (type === 'nature') {
    // 院校性质 公办、民办、中外/港澳
    // console.log(natureTypeIndex, '没激活', natureArray);

    if (natureTypeIndex.value.includes(code)) {
      natureTypeIndex.value = natureTypeIndex.value.filter((i) => i !== code);
      natureArray.value = natureArray.value.filter((obj) => obj.code !== code);
    } else {
      natureTypeIndex.value.push(code);
      natureArray.value.push(selectedItem);
    }
  }
  if (type === 'school_feature') {
    // 院校层次
    if (code === 0) {
      featureIndexs.value = [0];
      levelArray.value = [];
    } else {
      if (featureIndexs.value.includes(code)) {
        featureIndexs.value = featureIndexs.value.filter((i) => i !== code);

        levelArray.value = levelArray.value.filter((obj) => obj.code !== code);

        if (featureIndexs.value.length == 0) {
          featureIndexs.value = [0];
        }
      } else {
        if (featureIndexs.value.includes(0)) {
          featureIndexs.value = featureIndexs.value.filter((i) => i !== 0);
          levelArray.value = levelArray.value.filter((obj) => obj.code !== 0);
        }
        featureIndexs.value.push(code);
        levelArray.value.push(selectedItem);
      }
    }
  } else if (type === 'type') {
    // 院校类型
    if (code === 0) {
      typeIndexs.value = [0];
      typeArray.value = [];
    } else {
      if (typeIndexs.value.includes(code)) {
        typeIndexs.value = typeIndexs.value.filter((i) => i !== code);
        typeArray.value = typeArray.value.filter((obj) => obj.code !== code);

        if (typeIndexs.value.length == 0) {
          typeIndexs.value = [0];
        }
      } else {
        if (typeIndexs.value.includes(0)) {
          typeIndexs.value = typeIndexs.value.filter((i) => i !== 0);
          typeArray.value = typeArray.value.filter((obj) => obj.code !== 0);
        }
        typeIndexs.value.push(code);
        typeArray.value.push(selectedItem);
      }
    }
  } else if (type === 'province') {
    // 院校省份
    if (code === '0') {
      provinceIndexs.value = ['0'];
      provinceArray.value = [];
    } else {
      if (provinceIndexs.value.includes(code)) {
        provinceIndexs.value = provinceIndexs.value.filter((i) => i !== code);
        provinceArray.value = provinceArray.value.filter(
          (obj) => obj.code !== code
        );

        if (provinceIndexs.value.length == 0) {
          provinceIndexs.value = ['0'];
        }
      } else {
        if (provinceIndexs.value.includes('0')) {
          provinceIndexs.value = provinceIndexs.value.filter((i) => i !== '0');
          provinceArray.value = provinceArray.value.filter(
            (obj) => obj.code !== '0'
          );
        }
        provinceIndexs.value.push(code);
        provinceArray.value.push(selectedItem);
      }
    }
  } else if (type == 'schoolSearch') {
    // 这里只处理删除逻辑 添加逻辑在 onClickSearchItem 函数中
    searchArray.value = searchArray.value.filter((i) => i.code !== code);
  } else if (type == 'ssearch') {
    // 这里只处理删除逻辑 添加逻辑在 onClickSearchItem 函数中
    searchArray.value = searchArray.value.filter((i) => i.type !== 'ssearch');
  }

  console.log(levelArray.value, 'levelArray.value ');
  selItemArray.value = [
    ...provinceArray.value,
    ...typeArray.value,
    ...levelArray.value,
    ...natureArray.value,
    ...searchArray.value,
  ];

  saveSchoolInfoChange(selItemArray.value);
}

const saveSchoolInfoChange = _.throttle((val) => {
  if (props.storeType == 1) {
    userSearchValTool.saveSchoolInfoChange(val);
  } else if (props.storeType == 2) {
    userSearchValMajorTool.saveSchoolInfoChange(val);
  } else {
    userSearchVal.saveSchoolInfoChange(val); // 保存到 store 中
  }
}, 800);

// 搜索输入值改变
let reg_test = ref(null);
const searchKeyInput = _.throttle((val) => {
  console.log(props.batch, '=====');

  if (/^1段|本.*$/.test(props.batch)) {
    reg_test.value = 'ben';
  } else if (
    /^2段|^3段|^专.*$/.test(props.batch) ||
    ['中职单招', '高职单招'].includes(props.batch)
  ) {
    reg_test.value = 'zhuan';
  } else {
    reg_test.value = 'gao_ben';
  }

  console.log('wwss', props.batch, reg_test.value);
  if (val.length >= 2) {
    searchSchool({
      search: val,
      pageSize: 1000,
      studentId: props.studentId,
      is_danzhao: localStorage.getItem('zhigao'),
    }).then((res) => {
      searchList.value = res.data;

      searchList.value.splice(0, 0, searchKey.value);
      //   2段代表专科     1段代表本科  gao_ben  该批次未招生 eduLevel cnName
      // if (!!props.batch) {
      if (['1', '2'].includes(localStorage.getItem('zhigao'))) {
        searchList.value.forEach((v) => {
          if (v.cnName && reg_test.value != v.eduLevel) {
            v.cnName = `${v.cnName}(该批次未招生)`;
          }
        });
      }

      // }
      isShowSearchPop.value = true;
    });
  } else {
    searchList.value = [];
    isShowSearchPop.value = false;
  }
}, 800);
const toggleAll = (val) => {
  if (val) {
    // 全选操作
    props.schoolData.forEach((v) => {
      v.isChange = true; // 标记为已选
      if (!Cities.checkedCities.includes(v.code)) {
        Cities.checkedCities.push(v);
      }
    });

    // 将选中的项存储到 selItemArray
    if (Cities.checkedCities.length > 0) {
      Cities.checkedCities.forEach((item) => {
        const selectedItem = {
          code: item.code,
          name: item.cnName,
          type: 'schoolSearch',
        };

        let index = searchArray.value.findIndex((i) => i.code == item.code);
        if (index < 0) {
          searchArray.value.push(selectedItem);
          selItemArray.value = [
            ...provinceArray.value,
            ...typeArray.value,
            ...levelArray.value,
            ...natureArray.value,
            ...searchArray.value,
          ];

          if (props.storeType == 1) {
            userSearchValTool.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
          } else if (props.storeType == 2) {
            userSearchValMajorTool.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
          } else {
            userSearchVal.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
          }
        }
      });
    }
  } else {
    // props.schoolData.forEach((v) => {
    //   v.isChange = false; // 标记为未选
    //   const index = Cities.checkedCities.findIndex(
    //     (item) => item.code === v.code
    //   );
    //   if (index !== -1) {
    //     Cities.checkedCities.splice(index, 1); // 从 checkedCities 中移除该项
    //   }
    // });
    // console.log(Cities.checkedCities, '777777777777');
    Cities.checkedCities.forEach((item) => {
      const selectedItem = {
        code: item.code,
        name: item.cnName,
        type: 'schoolSearch',
      };
      handleSchoolSelection(
        selectedItem.type,
        selectedItem.code,
        selectedItem.name
      );
    });
  }
  visible.value = false;
};
//学校筛选
const schoolSubmit = () => {
  if (Cities.checkedCities.length !== schoolList.value.length) {
    isAllchecked.value = false;
  }
  if (Cities.checkedCities.length > 0) {
    Cities.checkedCities.forEach((item) => {
      const selectedItem = {
        code: item.code,
        name: item.cnName,
        type: 'schoolSearch',
      };

      let index = searchArray.value.findIndex((i) => i.code == item.code);
      if (index < 0) {
        searchArray.value.push(selectedItem);
        selItemArray.value = [
          ...provinceArray.value,
          ...typeArray.value,
          ...levelArray.value,
          ...natureArray.value,
          ...searchArray.value,
        ];

        if (props.storeType == 1) {
          userSearchValTool.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
        } else if (props.storeType == 2) {
          userSearchValMajorTool.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
        } else {
          userSearchVal.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
        }
      }
    });
  }
  visible.value = false;
};
const changeItem = () => {
  isAllchecked.value = Cities.checkedCities.length === props.schoolData.length;
};
function onClickSearchItem(item, index) {
  console.log('===aaa', item);
  if (item.cnName.includes('未招生')) {
    ElMessage.warning('该学校暂未招生');
    return;
  } else {
    if (index == 0) {
      // 模糊搜索
      const selectedItem = {
        code: 0,
        name: item,
        type: 'ssearch',
      };

      searchArray.value = searchArray.value.filter(
        (obj) => obj.type !== 'ssearch'
      );
      searchArray.value.push(selectedItem);

      selItemArray.value = [
        ...provinceArray.value,
        ...typeArray.value,
        ...levelArray.value,
        ...natureArray.value,
        ...searchArray.value,
      ];

      if (props.storeType == 1) {
        userSearchValTool.saveSchoolInfoChange(selItemArray.value);
      } else if (props.storeType == 2) {
        userSearchValMajorTool.saveSchoolInfoChange(selItemArray.value);
      } else {
        userSearchVal.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
      }
    } else {
      // 精准学校code搜索
      const selectedItem = {
        code: item.code,
        name: item.cnName,
        type: 'schoolSearch',
      };

      let index = searchArray.value.findIndex((i) => i.code == item.code);
      if (index < 0) {
        searchArray.value.push(selectedItem);
        selItemArray.value = [
          ...provinceArray.value,
          ...typeArray.value,
          ...levelArray.value,
          ...natureArray.value,
          ...searchArray.value,
        ];

        if (props.storeType == 1) {
          userSearchValTool.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
        } else if (props.storeType == 2) {
          userSearchValMajorTool.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
        } else {
          userSearchVal.saveSchoolInfoChange(selItemArray.value); // 保存到 store 中
        }
      }
    }

    // 添加后清除搜索数据
    searchKey.value = '';
    searchList.value = [];
    isShowSearchPop.value = false;
  }
}

/**
 * 获取院校筛选数据
 */
function getSearchDate() {
  searchSchoolFilter({
    studentId: props.studentId,
    fronttype: '3',
  }).then((res) => {
    console.log(res, '院校层次');

    provincelist.value = res.data.province; // 省份
    //schoolType.value = res.data.categories; // 院校类型
    schoolType.value = ['不限', ...res.data.categories_danzhao]; // 院校类型
    // studentType.value = [...res.data.features];
    studentType.value = ['不限', ...res.data.features_danzhao];
    natureTypelist.value = res.data.natureType;
    fTypelist.value = res.data.eduLevel;
    schoolNewlylist.value = res.data.schoolNewly;
  });
}

// 快速通道
const fastTrack = (num, tag) => {
  localStorage.setItem('zntbProvinceId', props.zntbProvinceId);
  localStorage.setItem('zntbScore', props.zntbScore);

  if (num == 1) {
    drawertoolRef.value.handleChangeDrawer(true, '3-1', null, tag);
  } else if (num == 2) {
  } else if (num == 3) {
    drawertoolRef.value.handleChangeDrawer(true, 2, null, 0);
  } else if (num == 4) {
    drawertoolRef.value.handleChangeDrawer(true, 5, null, 1);
  } else if (num == 5) {
    drawertoolRef.value.handleChangeDrawer(true, 5, null, 2);
  }
};
function closeV() {
  visible.value = false;
}
onMounted(() => {
  getSearchDate();
});

defineExpose({
  deleteScreenItem,
  deleteAll,
  closeV,
});
</script>
<style lang="scss" scoped>
.flexend {
  div {
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-right: 20px;
    cursor: pointer;
  }
}
.major-left {
  width: 100px;
  font-size: 14px;
  text-align: center;
  color: #9b9b9b;
}
.major {
  display: flex;
  margin-top: 10px;

  .major-right {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .major-size {
      font-size: 14px;
      margin-bottom: 12px;
      padding: 4px 16px;
      margin-right: 10px;
      text-align: center;
      border: 1px solid #e5e6eb;
      border-radius: 4px;
      cursor: pointer;
      color: #4e5969;
    }

    .active {
      border: 1px solid #004cf7;
      color: #004cf7;
    }
  }
}

.search-popover {
  position: absolute;
  top: 40px;
  left: 0;
  width: 240px;
  height: 200px;
  overflow: auto;
  background-color: white;
  z-index: 999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  border: 1px solid #c9cdd4;
  padding: 0 10px;
  font-size: 14px;
}
</style>
